import React, { PureComponent } from 'react';
import { Input } from 'antd';

const removeBrackets = value => (value ? value.replace(/[【】]/g, '') : '');
const addBrackets = value => (value ? `【${value}】` : '');

class SmsSignInput extends PureComponent {
  state = {
    value: '',
  };

  componentWillMount() {
    const { props } = this;
    if (props.value) this.setStateValue(props.value);
  }

  componentWillReceiveProps(nextProps) {
    const { props } = this;
    if (props.value !== nextProps.value && !nextProps.value) {
      this.setStateValue('');
    } else {
      this.setStateValue(nextProps.value);
    }
  }

  setStateValue = value => {
    this.setState({ value: removeBrackets(value) });
  };

  handleChangeValue = e => {
    const { value } = e.target;
    const { onChange } = this.props;
    this.setState({ value });
    if (onChange) onChange(addBrackets(value));
  };

  render() {
    const { value } = this.state;
    const { props } = this;
    return <Input {...props} value={value} onChange={this.handleChangeValue} />;
  }
}

export default SmsSignInput;
